package org.jeecg.modules.system.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysHomePageLayout;
import org.jeecg.modules.system.mapper.SysHomePageLayoutMapper;
import org.jeecg.modules.system.service.ISysHomePageLayoutService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 首页配置
 * @Author: jeecg-boot
 * @Date:   2021-02-03
 * @Version: V1.0
 */
@Service
public class SysHomePageLayoutServiceImpl extends ServiceImpl<SysHomePageLayoutMapper, SysHomePageLayout> implements ISysHomePageLayoutService {

	/**
	 * 通过当前登录人查询
	 */
	@Override
	public SysHomePageLayout getSysHomePageLayoutByMap(Map<String, Object> parameter) {
		SysHomePageLayout sysHomePageLayout = null;
		List<SysHomePageLayout> sysHomePageLayoutList = null;
		// 查询默认的布局
		if(MapUtils.isNotEmpty(parameter) 
				&& parameter.get("isDefaultLayout") != null 
				&& CommonConstant.STATUS_1.equals(parameter.get("isDefaultLayout").toString())) {
			sysHomePageLayoutList = this.baseMapper.selectList(new LambdaQueryWrapper<SysHomePageLayout>()
					.eq(SysHomePageLayout::getIsDefaultLayout, CommonConstant.STATUS_1)
					);
			if(!CollectionUtils.isEmpty(sysHomePageLayoutList)) {
				sysHomePageLayout = sysHomePageLayoutList.get(0);
			}
		} else {
			// 查询当前登录用户已保存的布局
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			sysHomePageLayoutList = this.baseMapper.selectList(new LambdaQueryWrapper<SysHomePageLayout>()
					.eq(SysHomePageLayout::getCreateBy, sysUser.getUsername())
					.eq(SysHomePageLayout::getIsDefaultLayout, CommonConstant.STATUS_0)
					);
			if(!CollectionUtils.isEmpty(sysHomePageLayoutList)) {
				sysHomePageLayout = sysHomePageLayoutList.get(0);
			} else {
				// 查询默认的布局
				sysHomePageLayoutList = this.baseMapper.selectList(new LambdaQueryWrapper<SysHomePageLayout>()
						.eq(SysHomePageLayout::getIsDefaultLayout, CommonConstant.STATUS_1)
						);
				if(!CollectionUtils.isEmpty(sysHomePageLayoutList)) {
					sysHomePageLayout = sysHomePageLayoutList.get(0);
					sysHomePageLayout.setId(null);
				}
			}
		}
		if(StringUtils.isNotEmpty(sysHomePageLayout.getLayoutJson())) {
			Object jsonData = JSONArray.parse(sysHomePageLayout.getLayoutJson());
			sysHomePageLayout.setJsonData(jsonData);
		}
		return sysHomePageLayout;
	}

}
